package com.crm.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import java.util.ArrayList;
import java.util.List;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {// implements HandlerInterceptor
	private List<String> excludedUrl = new ArrayList<>();
	{
		excludedUrl.add("login");
		excludedUrl.add("websocket");
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {



		// 允许跨域的主机地址
		response.setHeader("Access-Control-Allow-Origin", "*");

		// 获取请求路径，例如：/ent/list
		String requestUri = request.getRequestURI();

		System.out.println("地址：" + requestUri);
		for (String uri : excludedUrl) {
			if (requestUri.contains(uri)) {
				return true;
			}
		}
		// 获取用户每次请求时，携带的tokenId信息
		String token = request.getParameter("token");
		System.out.println("token：" + token);
		if (token != null && !token.equals("")) {
			return true;
		} else {
			response.sendRedirect("http://127.0.0.1:8020/yjwk_CRM/login.html");
		}
		return false;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
